# -*- coding: UTF-8 -*-
import pygame
from pygame.locals import *
import socket
from Const import *
import threading

class Server:
	def __init__(self):
		self.mapname = None
	def connect(self, host, nick, mdp):
		self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.flo = self.s.makefile('r',0)
		try:
			print "Connexion au serveur..."
			self.s.connect((host, 1228))
		except:
			print "Serveur non-atteignable"
			#self.mapname = "testmap.tmx"
			return False
		print "Envoi des donnees de connexion..."
		#print ("(" + str(CONNEXION) + " " + str(nick) + ";" + str(mdp) + "\n" + ")")
		self.s.send(str(CONNEXION) + " " + str(nick) + ";" + str(mdp) + "\n")
		data = None
		while not data:
			data = self.s.recv(1)
			if data:
				break
		cmds = data.split(" ")
		if cmds[0] == str(CONNECTED):
			print "Connecte avec succes"
		else:
			print "Identifiant et/ou mot de passe incorrect"
			return False
		mapname = None
		while not mapname:
			mapname = self.s.recv(64)
			if mapname:
				break
		print mapname
		self.mapname = 	mapname
		self.s.setblocking(True)
		print "Le protocole de connexion s'est termine joyeusement"
		
	def getInitInfo(self):
		return self.mapname
	def sendData(self,data):
		self.s.send(data)
		
		
	def commandsTread(self, continuer, ObjectHandler):
		while continuer:
			for lines in self.flo:
				cmds = lines.split(" ")
				if cmds[0] == str(MAPUPDATE):
					if cmds[1] == str(POSUPDATE):
						ObjectHandler.posUpdate(int(cmds[2]), cmds[3])
		time.sleep(0.03)
						
				
				
				
			
			
			
    
    
